from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
from .utils import Mypage
from question.utils import get_token_user
from .serializers import *


class ChannelsListView(ListAPIView):
    """获取频道"""
    queryset = Channel.objects.all()
    serializer_class = ChannelsSerializers
    pagination_class = Mypage


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializers
    pagination_class = Mypage

    def retrieve(self, request, *args, **kwargs):
        article = self.get_object()
        article.visits += 1
        article.save()
        return super().retrieve(request, *args, **kwargs)

    # 指定频道文章列表
    @action(methods=['get'], detail=True)
    def channel(self, request, pk):
        if pk != '-1':
            self.queryset = self.queryset.filter(channel_id=pk)
        return self.list(request)

    # 发布文章
    def create(self, request, *args, **kwargs):
        user = get_token_user(request)
        data = request.data
        data['channel_id'] = data.pop('channel')
        data['user'] = user
        labels = data.pop('labels')
        article = Article.objects.create(**data)
        article.labels.set(labels)
        return Response({'success': True, 'message': 'ok', 'articleid': article.id})

    # 收藏或取消收藏文章
    @action(methods=['put'], detail=True)
    def collect(self, request, pk):
        user = get_token_user(request)
        article = self.get_object()
        # au = user.collected_articles.filter(id=pk)
        au = article.collected_users.all().filter(id=user.id)
        if au:
            article.collected_users.remove(user.id)
        else:
            article.collected_users.add(user.id)
        return Response({'success': True, 'message': 'ok'})

    @action(methods=['post'], detail=True)
    def publish_comment(self, request, pk):
        user = get_token_user(request)
        article = self.get_object()
        data = request.data
        data.pop('article')
        data['article'] = article
        data['user'] = user
        Comment.objects.create(**data)
        return Response({'success': True, 'message': 'ok'})




# class ArticlesListView(ListAPIView):
#     queryset = Article.objects.all()
#     serializer_class = ArticleSerializers
#     pagination_class = Mypage
#
#     def get_queryset(self):
#         q = self.request.query_params.get('text')
#         return self.queryset.filter(title__contains=q)


#
# from drf_haystack.viewsets import HaystackViewSet
# class ArticalViewSet(HaystackViewSet):
#     index_models = [Article]
#     serializer_class = ArticleIndexSerializer
#     pagination_class = Mypage

